package com.btpj.module_main.ui.nav

import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import com.btpj.jetpack.base.BaseFragment
import com.btpj.jetpack.arouter.webview.WebViewServiceImpWrap
import com.btpj.module_main.R
import com.btpj.module_main.adapter.NavItemDetailAdapter
import com.btpj.module_main.data.entity.NavItemDetail
import com.btpj.module_main.databinding.FragmentNavDataPageBinding
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.fragment_nav_data_page.*

class NavDataPageFragment : BaseFragment<NavDataPageViewModel, FragmentNavDataPageBinding>() {

    private val mDetailList: MutableList<NavItemDetail> = ArrayList()
    private val mAdapter by lazy { NavItemDetailAdapter() }

    override fun getLayoutId() = R.layout.fragment_nav_data_page

    companion object {
        fun newInstance(navItemDetails: MutableList<NavItemDetail>) =
            NavDataPageFragment().apply {
                arguments = Bundle().apply {
                    putString("data", Gson().toJson(navItemDetails))
                }
            }
    }

    override fun initView() {
        recyclerView.apply {
            layoutManager = GridLayoutManager(requireContext(), 2)
            adapter = mAdapter
        }

        Gson().fromJson<MutableList<NavItemDetail>>(
            requireArguments().getString("data"),
            object : TypeToken<MutableList<NavItemDetail>>() {}.type
        ).let {
            mDetailList.addAll(it)
            mAdapter.setList(mDetailList)
            mAdapter.notifyDataSetChanged()
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            val detailItem = mDetailList[position]
            WebViewServiceImpWrap.instance.start(
                requireContext(),
                detailItem.title,
                detailItem.link
            )
        }
    }
}